package com.orhon.smartcampus.modules.base.mutation;

import com.alibaba.fastjson.JSON;
import com.orhon.smartcampus.basicComponents.Result;
import com.orhon.smartcampus.modules.base.dao.DictionaryDao;
import com.orhon.smartcampus.modules.base.entity.Dictionary;
import com.orhon.smartcampus.modules.base.gqlInputModel.GQLDictionaryInput;
import com.orhon.smartcampus.modules.base.inputMapper.DictionaryInputMapper;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class AddDictionaryMutation implements DataFetcher {


    @Autowired
    DictionaryDao dictionaryDao;

    /**
     * 新增/修改数据字典
     * editor : ths
     */
    @Override
    public Object get(DataFetchingEnvironment environment) throws Exception {

        GQLDictionaryInput input = DictionaryInputMapper.MAPPER.mapInput(environment.getArgument("inputData"));

        Dictionary dictionary = null;

        if (input.getId() != null) {
            dictionary = dictionaryDao.get(Dictionary.class, input.getId());
            dictionary.setUpdatedAt(new Date());
        } else {
            dictionary = new Dictionary();
            dictionary.setCreatedAt(new Date());
        }

        if(input.getName() != null){
            dictionary.setDictionaryName(JSON.toJSONString(input.getName()));
        }
        if(input.getValue() != null){
            dictionary.setValueCode(input.getValue());
        }
       if(input.getDictionary_code() != null){

           dictionary.setDictionaryCode(input.getDictionary_code());
       }
       if(input.getDescription() != null){
           dictionary.setDictionaryDescription(JSON.toJSONString(input.getDescription()));
       }
       if(input.getType() != null){

           dictionary.setType(input.getType());
       }
        if(input.getParent_id() != null){

            dictionary.setParent_id(input.getParent_id());
        }
        if(input.getAlias() != null){

            dictionary.setAlias(input.getAlias());
        }
        if(input.getStatus() != null){

            dictionary.setStatus(input.getStatus());
        }
        if(input.getMeta() != null){

            dictionary.setMeta(input.getMeta());
        }
        try {
            dictionaryDao.saveOrUpdate(dictionary);
        } catch (Exception e) {
            return Result.error(500, "" + e);
        }
        return Result.ok();
    }
}

